<template>
  <el-dialog
    title="手写签名"
    class="config-dialog"
    :visible.sync="signVisible"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    append-to-body
    width="900px"
    @open="openhands"
    @closed="closehands"
  >
    <div class="showcode">
      <span class="title">扫码签名</span>
      <div ref="qrCodeDiv" class="qrCodeDiv"></div>
      <div class="trangle"></div>
    </div>

    <div class="content">
      <div v-if="signVisible" id="signSure" class="signSure">
        <canvas
          class="whiteBord"
          id="whiteBord"
          :style="imageUrlT && 'visibility: hidden'"
        >
        </canvas>
        <img
          v-if="imageUrlT"
          :src="imageUrlT"
          alt=""
          :draggable="false"
          class="whiteBord img"
        />
        <div class="btnBox">
          <div class="colorBox">
            <div
              class="color"
              v-for="(item, index) in colorList"
              :key="index"
              @click="changeColor(index)"
              :class="selected == index && 'selected'"
              :style="`background: ${item}`"
            ></div>
          </div>
          <font-size className="pc" @change="handleChangeSlider" />
          <button class="primaryBtn" id="againWrite">重写</button>
          <button class="primaryBtn activeBtn" id="sureWrite">确定</button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import FontSize from './fontSize'
import QRCode from 'qrcodejs2';
import {signature, changeOri} from "./signature";
import { upload } from "@/api/basicData/seal";

export default {
  name: "Sign",
  components: {
    FontSize
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ws: null,
			imageUrlT: null,
			colorList: ["#000", 'red', 'blue'], /* 颜色列表 */
			selected: 0, /* 选中的颜色 */
    };
  },
  computed: {
    signVisible: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", val);
      },
    },
  },
  methods: {
    openhands() {
      this.showSign({
        userId: this.$store.state.user.userId
      })
    },
    // 打开手写签名
    showSign(row) {
      this.signVisible = true;
      this.imageUrlT = null;
      this.$nextTick(() => {
        let params = {
          whiteBord: "whiteBord", //canvas标签的id名称
          againWrite: "againWrite", //重写按钮id名
          sureWrite: "sureWrite", //确认按钮id名
          maxFonts: 20,
          minFonts: 16,
          clearWriteCallback: () => {
            //重写的回调函数
            this.imageUrlT = null;
          },
          sureWriteCallback: (imageBase64) => {
            //签名完成后的回调函数
            this.suresign(imageBase64, row);
          },
        };
        signature(params);
        let VUE_APP_CONTEXT_PATH =
          process.env.VUE_APP_CONTEXT_PATH == "/"
            ? ""
            : process.env.VUE_APP_CONTEXT_PATH;
        let url =
          "http://" +
          document.location.host +
          VUE_APP_CONTEXT_PATH +
          "/handsf?userId=" +
          row.userId;
        console.log("url", url);
        this.qrcode = new QRCode(this.$refs.qrCodeDiv, {
          text: url,
          width: 100,
          height: 100,
          colorDark: "#333333", //二维码颜色
          colorLight: "#ffffff", //二维码背景色
          correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
        });
        let prefixUrl = `ws://${document.location.host}${process.env.VUE_APP_BASE_API}/ws/signature/`;
        //创建WebSocket连接对象
        this.ws = new WebSocket(prefixUrl + row.userId);
        //连接成功建立
        this.ws.onopen = function (event) {
          console.log("建立连接", event);
        };
        //接收到消息
        this.ws.onmessage = (event) => {
          console.log("接收到内容：" + event.data);
          if (event.data) {
            this.$set(this, "imageUrlT", "data:image/png;base64," + event.data);
          }
        };
        //连接发生错误
        this.ws.onerror = function (event) {
          console.log("发生错误");
        };
        //连接关闭
        this.ws.onclose = function (event) {
          console.log("关闭连接");
        };
      });
    },
    handleChangeSlider(val) {
      changeOri("changeSize", null, {
        maxFonts: val,
        minFonts: val - 4,
      });
    },
    // 签名完成
    suresign(imageBase64, row) {
      // console.log("imageBase64", imageBase64);
      let base64;
      if (this.imageUrlT) {
        /* 上传的图片 */
        base64 = this.imageUrlT;
      } else if (imageBase64 != "empty") {
        /* 绘制的图片 */
        base64 = imageBase64;
      } else {
        this.$modal.msgWarning("签名不能为空");
        return;
      }

      let blob = this.dataURLtoBlob(base64);
      let file1 = this.blobToFile(blob, "handsfile");
      let fd = new FormData();
      fd.append("file", file1);
      upload(fd).then((response) => {
        console.log("uploadResponse", response);
        this.$modal.msgSuccess("签名成功")
        this.signVisible = false;
        this.ws.close();
        this.$emit("sign-success", response.data);
      });
    },
    // 将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    // 将blob转换为file
    blobToFile(theBlob, fileName) {
      theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
      theBlob.name = fileName; // 文件名
      return new File([theBlob], fileName, {
        type: theBlob.type,
        lastModified: Date.now(),
      });
    },
    // 更改颜色
    changeColor(index) {
      this.selected = index;
      changeOri("changeColor", this.colorList[index]);
    },
    // 关闭手写弹框
    closehands() {
      console.log("closehands");
      let qrCodeDiv = document.getElementsByClassName("qrCodeDiv");
      qrCodeDiv[0].innerHTML = "";
      this.ws.close();
    },
  },
};
</script>

<style scoped lang="scss">
.config-dialog {
  ::v-deep .el-dialog__body {
    padding: 0;
  }
}
.showcode {
  position: absolute;
  top: 7px;
  right: 118px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  width: 108px;
  z-index: 1;
  cursor: pointer;
  .title {
    line-height: 50px;
    color: #3c3c3c;
  }
  &:hover {
    .qrCodeDiv {
      display: block;
    }
    .trangle {
      display: block;
    }
  }
  .qrCodeDiv {
    border: 1px solid #999;
    padding: 3px;
    // height: 0;
    display: none;
    transition: all 0.3s;
    margin-top: -3px;
  }
  .trangle {
    border-top: 7px solid transparent;
    border-right: 7px solid transparent;
    border-bottom: 7px solid #434343;
    border-left: 7px solid transparent;
    position: absolute;
    top: 33px;
    right: 48px;
    display: none;
  }
}
.content {
  height: 383px;
}
.signSure {
  border-radius: 16px;
  position: relative;
  .topTitle {
    margin: 20px 0 12px 12px;
    font-size: 16px;
  }
  .whiteBord {
    width: 100%;
    height: 300px;
    border-bottom: 1px solid #eee;
    margin: 0 auto;
    border-radius: 4px;
    cursor: pointer;
    &.img {
      position: absolute;
      top: 0;
      right: 0;
      cursor: not-allowed;
    }
  }
  .btnBox {
    padding: 20px 50px;
    display: flex;
    justify-content: space-between;
    .colorBox {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      .color {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        margin-right: 10px;
        &:hover {
          cursor: pointer;
        }
      }
      .selected {
        transform: scale(1.3);
      }
    }
    .primaryBtn {
      width: 40%;
      height: 40px;
      color: #666;
      border: 1px solid #ccc;
      border-radius: 4px;
      background: #fff;
      cursor: pointer;
      transition: 0.4s cubic-bezier(0.175, 0.885, 0.32, 1);
      transition-property: background, border, box-shadow, outline, opacity;
      &:hover {
        background-color: #dedede;
        border-color: #a1a1a1;
        box-shadow: 0 2px 1px rgba(0, 0, 0, 0.1);
      }
      &:nth-of-type(1) {
        margin-right: 30px;
      }
    }
    .activeBtn {
      background: #2A72EE;
      color: #fff;
      border: none;
      &:hover {
        background-color: #46a6ff;
      }
    }
  }
}
</style>
